package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user/user")
@Api("用户端相关接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("微信用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> wxUserLogIn(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("开始进行微信用户登录，要用授权码：{}", userLoginDTO.getCode());
        User user=userService.wxLogIn(userLoginDTO);
        //逻辑是先进行登录，登陆成功后用JwtUtil工具类 “生成” jwt令牌
        Map claims=new HashMap<>();//必须初始化？
        claims.put(JwtClaimsConstant.USER_ID,user.getId());//在集合里面放一下这个用户信息，生成独一无二的jwt令牌
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //不用builder构建器的方式新建对象
        UserLoginVO userLoginVO=new UserLoginVO();
        userLoginVO.setToken(token);
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(user.getOpenid());

        return Result.success(userLoginVO);
    }

}
